<template>
  <div>
    <h3>我的购物车界面内容</h3>
    <div class="items" v-for="item in cartList" :key="item.id">
      <div>商品名称: {{ item.goods.goodsName }}</div>
      <div>商品数量: {{ item.count }}</div>
      <div>
        <button @click="addCart(item)">+</button>
        <button @click="reduceCart(item)">-</button>
      </div>
      <div>商品价格:$ {{ item.goods.goodsPrice }}</div>
      <div>商品总价:$ {{ item.goods.goodsPrice * item.count }}</div>
      <hr />
    </div>
    <hr />
    <div>合计$ {{ sum }}</div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "CartList",
  methods: {
    addCart(item) {
      this.$store.commit("ADD_CART", item.goods);
    },
    reduceCart(item) {
      this.$store.commit("REDUCE_CART", item.goods);
    },
  },
  computed: {
    ...mapState({
      cartList(state) {
        return state.cart.cartList;
      },
    }),
    sum() {
      return this.cartList.reduce((total, item) => {
        return total + item.goods.goodsPrice * item.count;
      }, 0);
    },
  },
  mounted() {
    console.log(this.cartList);
  },
  // beforeRouteEnter: (to, from, next) => {
  //   console.log(to.path);
  //   if (localStorage.getItem("token")) {
  //     next();
  //   } else {
  //     next(`/login?cb=${to.path}`);
  //   }
  // },
};
</script>

<style scoped></style>
